package com.xyyl.patient.core.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xyyl.patient.core.constant.HttpStatusEnum;
import com.xyyl.patient.core.constant.SystemConstant;
import com.xyyl.patient.core.support.Pager;
import com.xyyl.patient.core.util.PageData;
import com.xyyl.patient.core.util.StringUtils;

/**
 * @projectName:xyyl-patient-web
 * @ClassName: BaseController
 * @Description:BaseController
 * @author chens
 * @date 2017年8月23日
 */
public class BaseController {

	private Logger logger = LogManager.getLogger(getClass());

	public PageData getPageData() {
		return new PageData(this.getRequest());
	}

	/**
	 * 得到request对象
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return request;
	}

	@ExceptionHandler(Exception.class)
	public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
			throws Exception {
		
		logger.error("SOME ERRORS OCCURED! AS FOLLOWS :{}", ex.getMessage().toString());
		
		ModelMap modelMap = new ModelMap();
		modelMap.put("status", HttpStatusEnum.SERVER_ERROR.getCode());
		modelMap.put("returnmemo", HttpStatusEnum.SERVER_ERROR.getDescription());
		modelMap.put("operateTime", System.currentTimeMillis());
		modelMap.put("msg", HttpStatusEnum.SERVER_ERROR.getMsg());
		response.setContentType(SystemConstant.ContentType);
		byte[] bytes = JSON.toJSONBytes(modelMap, SerializerFeature.DisableCircularReferenceDetect);
		response.getOutputStream().write(bytes);
		response.getOutputStream().close();
	}

	public Pager initPage() {

		Pager pager = new Pager();
		PageData pd = this.getPageData();
		if (pd != null) {
			pager.setPageData(pd);
		}

		String pageNo = pd.getString(SystemConstant.PAGE.PAGENO);
		if (StringUtils.isNotEmpty(pageNo)) {
			pager.setPageNo(Integer.parseInt(pageNo) < 1 ? 1 : Integer.parseInt(pageNo));
		}

		String pageSize = pd.getString(SystemConstant.PAGE.PAGESIZE);
		if (StringUtils.isNotEmpty(pageSize)) {
			pager.setPageSize(Integer.parseInt(pageSize));
		}

		String orderBy = pd.getString(SystemConstant.PAGE.ORDERBY);
		if (StringUtils.isNotEmpty(orderBy)) {
			pager.setOrderBy(orderBy);
		}

		String sort = pd.getString(SystemConstant.PAGE.SORT);
		if (StringUtils.isNotEmpty(sort)) {
			pager.setSort(sort);
		}
		return pager;
	}

}
